package com.daoshu.socket.notice.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daoshu.socket.view.PushMessageIn;
import com.daoshu.socket.config.NoticeTypeEnum;
import com.daoshu.socket.config.WebsocketConfig;
import com.daoshu.socket.notice.ISyncMessageNotice;
import com.daoshu.socket.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: SyncMessageNoticeHttp
 * @description: Http 广播
 * @author: Allen
 * @create: 2019-07-29 09:10
 **/
@Slf4j
@Component("syncMessageNoticeHttp")
public class SyncMessageNoticeHttp implements ISyncMessageNotice {

    @Autowired
    WebsocketConfig websocketConfig;

    @Autowired
    IUserService userService;


    /*@Value("${eureka-user-name}")
    private String eurekaUserName;

    @Value("${eureka-user-password}")
    private String eurekaUserPassword;


    @Value("${eureka-server-port}")
    private String eurekaServerPort;

    @Value("${eureka-server-host}")
    private String eurekaServerHost;

    @Value("${spring.application.name}")
    private String serverId = "mti-service-socket";*/

    @Value("${server.port}")
    private String serverPort;

    @Override
    public void initializer() {
        log.info("SyncMessageNoticeHttp");
        if (!NoticeTypeEnum.HTTP.getName().equalsIgnoreCase(websocketConfig.getNoticeType())) {
            return;
        }
        log.info("SyncMessageNoticeHttp initializer");
    }

    @Override
    public void sendMessageNotice(PushMessageIn pushMessageIn) {


        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //封装成一个请求对象
        HttpEntity entity = new HttpEntity(pushMessageIn, headers);
        Set<String> sets = getServers();
        if (sets.size() == 1) {
            userService.sendMessageForUser(pushMessageIn);
            return;
        }

        sets.forEach(s -> {
            try {
                String url = s + "websocket/push/message";
                log.info("sendMessageNotice url===>>>> " + url);
                ResponseEntity<String> userResponseEntity = restTemplate.postForEntity(url, entity, String.class);
                log.info(" sendMessageNotice http getStatusCode()" + userResponseEntity.getStatusCode());
            } catch (Exception e) {
                log.error("sendMessageNotice http error:" + e.getMessage());
            }
        });

    }

    @Override
    public void monitorMessageNotice(PushMessageIn pushMessageIn) {
        log.info("monitorMessageNotice , {}", pushMessageIn);
        userService.sendMessageForUser(pushMessageIn);
    }


    /***
     * 获取eureka服务上注册的serverId 列表
     * @return
     */
    public Set<String> getServers() {
        Set<String> homePageUrlSet = new HashSet();
        ResponseEntity<JSONObject> responseEntity = null;
       /* String url = "http://" + eurekaServerHost + ":" + eurekaServerPort + "/eureka/apps/" + serverId;
        Set<String> homePageUrlSet = new HashSet();
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(eurekaUserName, eurekaUserPassword));
        ResponseEntity<JSONObject> responseEntity = null;*/
        try {
            homePageUrlSet.add("http://localhost:" + serverPort + "/");
            return homePageUrlSet;
        } catch (Exception e) {
            log.error("getServers err:" + e.getMessage());
        }

        if (responseEntity == null || responseEntity.getBody() == null) {
            return Collections.emptySet();
        }

        JSONObject application = responseEntity.getBody().getJSONObject("application");
        if (application == null) {
            return Collections.emptySet();
        }
        JSONArray instanceArr = application.getJSONArray("instance");
        if (instanceArr == null) {
            return Collections.emptySet();
        }

        for (int i = 0; i < instanceArr.size(); i++) {
            JSONObject jsonObject = instanceArr.getJSONObject(i);
            homePageUrlSet.add(jsonObject.getString("homePageUrl"));
        }

        return homePageUrlSet;
    }
}
